package com.bjtu.ptsite.controller;

import com.bjtu.ptsite.mapper.PromotionRuleMapper;
import com.bjtu.ptsite.model.PromotionRule;
import com.bjtu.ptsite.model.PromotionRuleRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 *
 * 促销规则接口
 *
 * @author Zehao Wang, Junjie Zhang, Yutao Wei
 *
 */
@CrossOrigin
@RestController
@RequestMapping("/api/promotion-rules")
@RequiredArgsConstructor
public class PromotionRuleController {
    private final PromotionRuleMapper promotionRuleMapper;

    @PostMapping
    public ResponseEntity<PromotionRule> createRule(@RequestBody PromotionRuleRequest rule) {
        PromotionRule promotionRule = new PromotionRule();
        promotionRule.setId(System.currentTimeMillis() % 10000000000L);
        promotionRule.setConditionType(rule.conditionType());
        promotionRule.setActionType(rule.actionType());
        promotionRule.setThreshold(rule.threshold());
        promotionRule.setIsActive(rule.isActive());
        promotionRule.setValue(rule.value());
        if (rule.deleteTheSimilar()) {
            promotionRuleMapper.deleteByConditionAndAction(rule.conditionType(), rule.actionType());
        }
        // MyBatis-Plus插入操作（返回受影响行数）
        int result = promotionRuleMapper.insert(promotionRule);
        // 回填自增ID（需要数据库支持自增主键）
        return result > 0 ? ResponseEntity.ok(promotionRule) :
                ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }

    @GetMapping
    public ResponseEntity<List<PromotionRule>> getAllRules() {
        // 无条件查询全部记录
        return ResponseEntity.ok(promotionRuleMapper.selectList(null));
    }

    @PostMapping("/deactivate")
    public ResponseEntity<?> ifActivateRule(@RequestBody PromotionRuleDeactive rule) {
        promotionRuleMapper.updateById(rule.id(), rule.isActive());
        return ResponseEntity.ok().build();
    }
}//this is a comment
